package com.sdkj.recruit.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Date;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.sdkj.recruit.common.Constants;
import com.sdkj.recruit.model.Company;
import com.sdkj.recruit.model.PostInformation;
import com.sdkj.recruit.model.ResultCode;
import com.sdkj.recruit.model.ResultData;
import com.sdkj.recruit.model.SmsCode;
import com.sdkj.recruit.model.User;
import com.sdkj.recruit.service.IAliyunSmsService;
import com.sdkj.recruit.service.ICompanyService;
import com.sdkj.recruit.service.IQiNiuService;
import com.sdkj.recruit.service.IUserService;
import com.sdkj.recruit.util.DESEncryption;
import com.sdkj.recruit.util.MD5Util;
import com.sdkj.recruit.util.RandomUtil;
import com.sdkj.recruit.util.StringUtil;
import com.sdkj.recruit.vo.CompanyResumeVo;
import com.sdkj.recruit.vo.CompanyVo;
import com.sdkj.recruit.vo.LoginLogVo;
import com.sdkj.recruit.vo.PositionCollectionVo;
import com.sdkj.recruit.vo.PositionVo;
import com.sdkj.recruit.vo.ReportInfoVo;
import com.sdkj.recruit.vo.ResumeVo;
import com.sdkj.recruit.vo.SimpleModelVo;
import com.sdkj.recruit.vo.WeixinConfigVo;

@Controller
@Path("/company")
public class CompayController {

	@Autowired
	private ICompanyService service;

	@Autowired
	private IQiNiuService qiniu;

	@Autowired
	private IAliyunSmsService smsService;
	
	@Autowired
	private IUserService userService;
	
	private static final Logger logger = Logger.getLogger(CompayController.class);
	
	@Autowired
	private Mapper mapper;
	/**
	 * 企业注册
	 * 
	 * @param companyVo
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/register")
	public ResultData<Object> register(final CompanyVo companyVo, @Context final HttpServletRequest request) {

		// 验证码
		String checkCode =companyVo.getCheckCode();
		// 判断验证码
		SmsCode sms =userService.querySms(companyVo.getMobile(),2);
		if(sms ==null) {
			return ResultCode.error("验证码不存在", companyVo);
		}
		
		if(!checkCode.equals(sms.getCode())) {
			return ResultCode.error("验证码不正确", companyVo);
		}
		
		// 判断用户是否已经注册
		CompanyVo cvo =service.queryCompanyByMobile(companyVo.getMobile());
		if(cvo!=null) {
			return ResultCode.error("用户已经注册", companyVo);
		}
		
		// 解密码，然后再MD5加密
		String password =generalPassword(companyVo.getMobile(), companyVo.getPassword());
		companyVo.setPassword(password);
		return service.saveCompany(companyVo);
	}
	
	
	/**
	 * 保存企业办公环境
	 * @param companyVo
	 * @param request
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/saveCompanyPic")
	public ResultData<Object> saveCompanyPic(final CompanyVo companyVo, @Context final HttpServletRequest request) {
		
		final HttpSession session = request.getSession();
		User u =(User)session.getAttribute("recruit_login");
		companyVo.setCompanyId(u.getUserId());
		return service.saveCompanyPic(companyVo);
	}
	
	
	
	@POST
	@Path("/collectionResume")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED + ";charset=utf-8")
	public ResultData<Object> collectionResume(@FormParam("resumeIds[]") final List<String> resumeIds, @Context final HttpServletRequest request) {
		
		final HttpSession session = request.getSession();
		User u =(User)session.getAttribute("recruit_login");
		
		return service.collectionResume(u.getUserId(),resumeIds);
	}
	
	
	
	
	
	/**
	 * 保存职位
	 * @param positionVo
	 * @param request
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/savePosition")
	public ResultData<Object> savePosition(final PositionVo positionVo, @Context final HttpServletRequest request) {

		final HttpSession session = request.getSession();
		User u =(User)session.getAttribute("recruit_login");
		positionVo.setCompanyId(u.getUserId());
		return service.savePosition(positionVo);
	}
	
	
	/**
	 * 企业认证
	 * @param companyVo
	 * @param request
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/auth")
	public ResultData<Object> auth(final CompanyVo companyVo, @Context final HttpServletRequest request) {

		final HttpSession session = request.getSession();
		User u =(User)session.getAttribute("recruit_login");
		String companyId =u.getUserId();
		companyVo.setCompanyId(companyId);
		return service.auth(companyVo);
	}
	
	
	/**
	 * 更新职位
	 * @param positionVo
	 * @param request
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/updatePosition")
	public ResultData<Object> updatePosition(final PositionVo positionVo, @Context final HttpServletRequest request) {

		return service.updatePosition(positionVo);
	}
	
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/updateStatus")
	public ResultData<Object> updateStatus(@FormParam("id") final String  id,@FormParam("status") final int  status, @Context final HttpServletRequest request) {

		return service.updateStatus(id,status);
	}
	
	
	
	@Path("/check")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> check(@QueryParam("mobile")  final String mobile,
			@QueryParam("checkcode") final String checkcode, @QueryParam("type") final int type,
			@Context HttpServletRequest req) {
		
		// 判断验证码
		SmsCode sms =userService.querySms(mobile,type);
		if(sms ==null) {
			return ResultCode.error("验证失败", mobile);
		}
		return ResultCode.success("验证成功", mobile);
	}
	
	@Path("/bind")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> bind(@QueryParam("mobile")  final String mobile,
			@QueryParam("checkcode") final String checkcode, @QueryParam("type") final int type,
			@Context HttpServletRequest req) {
		
		// 判断验证码
		SmsCode sms =userService.querySms(mobile,type);
		if(sms ==null) {
			return ResultCode.error("验证失败", mobile);
		}
		
		// 修改手机号
		final HttpSession session = req.getSession();
		User u =(User)session.getAttribute("recruit_login");
		String companyId =u.getUserId();
		
		service.updateCompanyMobile(mobile,companyId);
		return ResultCode.success("验证成功", mobile);
	}
	
	/**
	 * 小程序，获取解密手机号
	 * @param encrypdata
	 * @param ivdata
	 * @param sessionkey
	 * @param req
	 * @return
	 */
	@Path("/deciphering")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> eciphering(@QueryParam("encrypdata")  final String encrypdata,
			@QueryParam("ivdata") final String ivdata, @QueryParam("uniqueId") final String uniqueId,
			@Context HttpServletRequest req) {

		Base64 b =new Base64();
		byte[] encrypData = b.decode(encrypdata);
		byte[] ivData = b.decode(ivdata);
		String str = "";
		try {
			//  获取sessionkey
			WeixinConfigVo wc =service.querySessionKeyByUniqueId(uniqueId);
			if(wc!=null) {
				byte[] sessionKey = b.decode(wc.getSession_key());
				str = decrypt(sessionKey,ivData,encrypData);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
        return ResultCode.success("解密成功", JSONObject.parse(str));
	}
	
	
	public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
		AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		return new String(cipher.doFinal(encData),"UTF-8");
	}
	
	/**
	 * 获取简历列表
	 * 所有用户的简历信息
	 * @param pageNo
	 * @param pageSize
	 * @param keyWord
	 * @param req
	 * @return
	 */
	@Path("/queryResumeList")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryResumeList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("keyWord") final String keyWord,@QueryParam("workYearType") final String workYearType,
			@Context HttpServletRequest req) {

		try {
			final HttpSession session = req.getSession();
			User u =(User)session.getAttribute("recruit_login");
			String companyId =u.getUserId();
			SimpleModelVo vo = new SimpleModelVo();
			List<ResumeVo> resumeList = service.queryResumeList(pageNo, pageSize, keyWord,companyId,workYearType);
			vo.setResumeList(resumeList);
			vo.setCount(service.queryAllResumeCount(keyWord,workYearType));
			return ResultCode.success("获取用户成功", vo);
		} catch (Exception e) {
			return ResultCode.error("获取用户失败", null);
		}
	}
	
	
	/**
	 * 岗位信息
	 * @param pageNo
	 * @param queryType
	 * @param req
	 * @return
	 */
	@Path("/queryPostIno")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryPostIno(@QueryParam("parentId") final String parentId,
			@QueryParam("queryType") final int queryType,
			@Context HttpServletRequest req) {

		return service.queryPostIno(parentId,queryType);
		
	}
	
	
	
	/**
	 * 获取简历详情
	 * @param pageNo
	 * @param pageSize
	 * @param keyWord
	 * @param req
	 * @return
	 */
	@Path("/queryResumeById/{resumeId}")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryResumeById(@PathParam("resumeId") final String  resumeId,
			
			@Context HttpServletRequest req) {

		try {
			ResumeVo resume =service.queryResumeById(resumeId);
			return ResultCode.success("获取简历成功", resume);
		} catch (Exception e) {
			return ResultCode.error("获取简历失败", null);
		}
	}
	
	
	
	/**
	 * 登录日志
	 * @param pageNo
	 * @param pageSize
	 * @param queryType 1:今天 2：历史
	 * @param req
	 * @return
	 */
	@Path("/queryLoginLogs")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryLoginLogs(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize,@QueryParam("queryType") final int queryType,
			@Context HttpServletRequest req) {

		try {
			final HttpSession session = req.getSession();
			User u =(User)session.getAttribute("recruit_login");
			String companyId =u.getUserId();
			SimpleModelVo vo = new SimpleModelVo();
			List<LoginLogVo> loginLogList = service.queryLoginLogs(pageNo, pageSize, companyId,queryType);
			vo.setLoginLogList(loginLogList);
			vo.setCount(service.queryAllLogsCount(companyId,queryType));
			return ResultCode.success("获取日志成功", vo);
		} catch (Exception e) {
			return ResultCode.error("获取日志失败", null);
		}
	}
	
	
	
	
	
	
	
	/**
	 * 发布职位职位列表
	 * @param pageNo
	 * @param pageSize
	 * @param keyWord
	 * @param req
	 * @return
	 */
	@Path("/queryPositionList")
	@GET
	public ResultData<Object> queryPositionList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("keyWord") final String keyWord,
			@Context HttpServletRequest req) {

		try {
			final HttpSession session = req.getSession();
			User u =(User)session.getAttribute("recruit_login");
			String companyId =u.getUserId();
			SimpleModelVo vo = new SimpleModelVo();
			List<PositionVo> positionList = service.queryPositionList(pageNo, pageSize, keyWord,companyId);
			vo.setPositionList(positionList);
			vo.setCount(service.queryAllPositionCount(keyWord,companyId));
			return ResultCode.success("获取用户成功", vo);
		} catch (Exception e) {
			return ResultCode.error("获取用户失败", null);
		}
	}
	
	
	/**
	 * 获取热门职位、排行榜服务、搜索服务
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param queryType 1:查询热门职位 2：排行榜（所有，时间先后顺序）3：搜索
	 * @param userId
	 * @param keyWord 关键词搜索
	 * @param req
	 * @return
	 */
	@Path("/queryPositions")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryPositions(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("queryType") final int queryType,
			@QueryParam("userId") final String userId, @QueryParam("keyWord") final String keyWord,
			@QueryParam("longitude") final String longitude,
			@QueryParam("latitude") final String latitude,
			@Context HttpServletRequest req) {
		try {
			return service.queryPositions(pageNo, pageSize, queryType,userId,longitude,latitude,keyWord);
		} catch (Exception e) {
			return ResultCode.error("查询失败", null);
		}
	}
	
	
	@Path("/updateLaction")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> updateLaction(
			@Context HttpServletRequest req) {
		service.updateLaction();
		return null;
	}
	
	@Path("/sethotCompany")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> sethotCompany(
			@Context HttpServletRequest req) {
		service.sethotCompany();
		return null;
	}
	
	/**
	 * 获取当前登录企业信息
	 * @param req
	 * @return
	 */
	@Path("/queryCompanyInfo")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryCompanyInfo(@Context HttpServletRequest req) {
		
		final HttpSession session = req.getSession();
		User u =(User)session.getAttribute("recruit_login");
		String companyId =u.getUserId();
		
		return service.queryCompanyById(companyId);
	}
	
	
	/**
	 * 获取企业职位列表
	 * @param pageNo
	 * @param pageSize
	 * @param companyId
	 * @param req
	 * @return
	 */
	@Path("/queryCompanyPositionList")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryCompanyPositionList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("companyId") final String companyId,@QueryParam("userId") final String userId,
			@Context HttpServletRequest req) {

		try {
			SimpleModelVo vo = new SimpleModelVo();
			List<PositionVo> positionList = service.queryPositionListNew(pageNo, pageSize,companyId,userId);
			vo.setPositionList(positionList);
			vo.setCount(service.queryAllPositionCount(companyId));
			return ResultCode.success("获取职位成功", vo);
		} catch (Exception e) {
			return ResultCode.error("获取职位失败", null);
		}
	}
	
	/**
	 * 上次附件信息
	 * @param type
	 * @param req
	 * @return
	 * @throws FileUploadException
	 */
	@Path("/uploadFile")
	@POST
	@ResponseBody
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> uploadFile(@QueryParam("type") final String type,@Context HttpServletRequest req) throws FileUploadException {
		
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
			List<FileItem> fileItems = servletFileUpload.parseRequest(req);

			if(fileItems.size()>0) {
				FileItem ft =fileItems.get(0);
				String url =qiniu.upload(ft.getInputStream());
				return ResultCode.success("上传成功", url);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ResultCode.success("上传失败", null);
	}
	
	
	/**
	 * 投递给我的简历
	 * @param pageNo
	 * @param pageSize
	 * @param keyWord
	 * @param req
	 * @return
	 */
	@Path("/queryDeliverResumeList")
	@GET
	public ResultData<Object> queryDeliverResumeList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("keyWord") final String keyWord,
			@Context HttpServletRequest req) {

		try {
			final HttpSession session = req.getSession();

			User u =(User)session.getAttribute("recruit_login");
			
			String companyId =u.getUserId();
			SimpleModelVo vo = new SimpleModelVo();
			List<CompanyResumeVo> deleiverList = service.queryDeliverResumeList(pageNo, pageSize, keyWord,companyId);
			vo.setDeleiverList(deleiverList);
			vo.setCount(service.queryAllDeliverResumeCount(keyWord,companyId));
			return ResultCode.success("获取用户成功", vo);
		} catch (Exception e) {
			return ResultCode.error("获取用户失败", null);
		}
	}
	
	
	
	
	/**
	 * 找回密码
	 * @param companyVo
	 * @param request
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/findPassword")
	public ResultData<Object> findPassword(final CompanyVo companyVo, @Context final HttpServletRequest request) {

		// 验证码
		String checkCode =companyVo.getCheckCode();
		// 判断验证码
		SmsCode sms =userService.querySms(companyVo.getMobile(),2);
		if(sms ==null) {
			return ResultCode.error("验证码不存在", companyVo);
		}
		
		if(!checkCode.equals(sms.getCode())) {
			return ResultCode.error("验证码不正确", companyVo);
		}
		
		// 判断用户是否已经注册
		CompanyVo cvo =service.queryCompanyByMobile(companyVo.getMobile());
		if(cvo==null) {
			return ResultCode.error("企业不存在，无法找回密码", companyVo);
		}
		
		// 解密码，然后再MD5加密
		String password =generalPassword(companyVo.getMobile(), companyVo.getPassword());
		
		companyVo.setRepassword(password);
		service.updatePassword(companyVo.getMobile(),password);
		
		return ResultCode.success("找回密码成功", companyVo);
	}
	
	
	
	/**
	 * @param userName
	 * @param password
	 * @return
	 */
	private String generalPassword(final String userName, final String password) {
		String decryptStr = "";
		try {
			decryptStr = DESEncryption.decrypt(password, userName);
		} catch (IOException e) {
			logger.error("Error in decrypt. Reason: " + e.getMessage());
		} catch (Exception e) {
			logger.error("Error in decrypt. Reason: " + e.getMessage());
		}

		if (userName.indexOf("@") != -1) {
			String shortUserName = userName.substring(0, userName.indexOf("@"));
			return MD5Util.string2MD5(shortUserName.toLowerCase() + Constants.USER_KEY + MD5Util.string2MD5(decryptStr));
		} else {
			return MD5Util.string2MD5(userName.toLowerCase() + Constants.USER_KEY + MD5Util.string2MD5(decryptStr));
		}
	}

	/**
	 * 企业登录
	 * @param mobile
	 * @param password
	 * @param request
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/login")
	public ResultData<Object> login(@FormParam("mobile") final String mobile,
			@FormParam("password") final String password, @Context final HttpServletRequest request) {

		// 后台管理登陆时必须输入验证码
		final HttpSession session = request.getSession();
		String accessToken = MD5Util.string2MD5(mobile + new Date().getTime());
		session.setMaxInactiveInterval(604800);// 设置session过期时间为1个小时，这里的以秒为单位的。
		Date lastLoginTime = new Date();
		// 判断用户是否存在
		CompanyVo companyVo = service.queryCompanyByMobile(mobile);
		if (companyVo == null) {
			return ResultCode.error("用户不存在，请选注册", null);
		}

		// 验证密码密码是否正确
		String psw = generalPassword(mobile, password);

		if (!psw.equals(companyVo.getPassword())) {
			return ResultCode.error("密码不正确", null);
		}

		
		// 验证密码密码是否正确
		String newpsw = generalPassword(password, password);
		//  生成新密码
		service.updateNewPassword(mobile, newpsw);
				
		companyVo.setLastLoginTime(lastLoginTime);
		companyVo.setAuthenticated(true);
		companyVo.setAccessToken(accessToken);
		companyVo.setMenus(userService.getUserMeuns(companyVo));
		Company company =mapper.map(companyVo, Company.class);
		// 记录登录日志
		service.registerLog(request,companyVo.getCompanyId());
		
		User user =mapper.map(company, User.class);
		user.setUserId(company.getCompanyId());
        session.setAttribute("recruit_login", user);
        companyVo.setCompanyDesc(null);
		return ResultCode.success("登录成功", companyVo);
	}

	
	/**
	 * 退出登录
	 * @param request
	 * @return
	 */
	@POST
    @Path("/logout")
	public ResultData<Object> logout(@Context final HttpServletRequest request) {

		ResultData<Object> result =new ResultData<>();

        final HttpSession session = request.getSession();
        final User user = (User) session.getAttribute("recruit_login");
        String userIosToken = null;
        String userId = null;
        if (user != null) {
            userId = user.getUserId();
        }
        logger.info("session user: " + user + "/" + userIosToken);

        service.cleanUserLoginInfo(userId);
        session.setAttribute("recruit_login", null);
        
        session.invalidate();
        result.setResCode(ResultCode.SUCCESS);
		return result;
    }
	
	/**
	 * 举报职位
	 * 
	 * @param reportVo
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/report")
	public ResultData<Object> report(ReportInfoVo reportVo) {

		return service.report(reportVo);
	}

	@Path("/sendSms")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> sendSms(@QueryParam("mobile") final String mobile,
			@QueryParam("codeType") final int codeType, @Context HttpServletRequest request) {

		String checkCode = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
		try {

			SendSmsResponse response = smsService.sendSms(mobile, checkCode, codeType);
			if (response.getCode() != null && response.getCode().equals("OK")) {
				return ResultCode.success("发送消息成功", response);
			}

		} catch (ClientException e) {
			return ResultCode.error(e.getErrMsg(), null);
		}
		return null;
	}
	
	
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/companyInfo/{companyId}")
	public ResultData<Object> queryCompanyById(@PathParam("companyId") final String companyId,
			@Context HttpServletRequest req) {

		return service.queryCompanyById(companyId);
	}
	
	
	/**
	 * 我的投递信息
	 * @param userId
	 * @param req
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/deliverList")
	public ResultData<Object> deliverList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("userId") final String userId,
			@Context HttpServletRequest req) {

		return service.deliverList(pageNo,pageSize,userId);
	}
	
	
	/**
	 * 职位收藏服务
	 * 
	 * @param userId
	 * @param positionId
	 * @param collectionType 1：收藏 2：取消 收藏
	 * @param req
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/collection/{userId}/{positionId}/{collectionType}")
	public ResultData<Object> collection(@PathParam("userId") final String userId,
			@PathParam("positionId") final String positionId,@PathParam("collectionType") final int collectionType, @Context HttpServletRequest req) {

		return service.collection(userId, positionId,collectionType);
	}
	
	
	/**
	 * 个人收藏列表
	 * @param pageNo
	 * @param pageSize
	 * @param userId
	 * @param req
	 * @return
	 */
	@Path("/querycollectionList")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> querycollectionList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("userId") final String userId,
			@Context HttpServletRequest req) {
		try {
			SimpleModelVo vo = new SimpleModelVo();
			List<PositionCollectionVo> collectionList = service.querycollectionList(pageNo, pageSize, userId);
			vo.setCollectionList(collectionList);
			vo.setCount(service.queryAllCollectionCount(userId));
			return ResultCode.success("查询成功", vo);
		} catch (Exception e) {
			return ResultCode.error("查询失败", null);
		}
	}
	
	/**
	 * 根据主键ID获取工作经验
	 * 
	 * @param companyId
	 * @param req
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/queryWorkExperienceById/{id}")
	public ResultData<Object> queryWorkExperienceById(@PathParam("id") final String id,
			@Context HttpServletRequest req) {

		return service.queryWorkExperienceById(id);
	}
	
	/**
	 * 根据主键ID获取教育信息
	 * 
	 * @param companyId
	 * @param req
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/queryEducationalExperienceById/{id}")
	public ResultData<Object> queryEducationalExperienceById(@PathParam("id") final String id,
			@Context HttpServletRequest req) {

		return service.queryEducationalExperienceById(id);
	}

	
	/**
	 * 获取职位详情
	 * 增加阅读记录数
	 * @param id
	 * @param req
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/initEditPosition")
	public ResultData<Object> initEditPosition(@QueryParam("id") final String id,@QueryParam("userId") final String userId,
			@Context HttpServletRequest req) {
		
		return service.initEditPosition(id,userId);
	}
	
	
	/**
	 * 获取职位详情
	 * @param id
	 * @param req
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/editPosition")
	public ResultData<Object> editPosition(@QueryParam("id") final String id,@QueryParam("userId") final String userId,
			@Context HttpServletRequest req) {
		return service.initEditPosition(id,userId);
	}


	
	
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/token")
	public ResultData<Object> token(@Context HttpServletRequest req) {

		return qiniu.uploadToken();
	}

	/**
	 * 删除企业信息
	 * 
	 * @param companyId
	 * @param req
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/deleteCompany/{companyId}")
	public ResultData<Object> deleteCompany(@PathParam("companyId") final String companyId,
			@Context HttpServletRequest req) {

		return service.deleteCompany(companyId);
	}

	
	/**
	 * 获取认证信息，用code 换取token
	 * @param userId
	 * @param code
	 * @param req
	 * @return
	 */
	@Path("/jscode2session")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> jscode2session(@QueryParam("code") final String code,
			@Context HttpServletRequest req) {
		return service.jscode2session(code);
	}
	
	/**
	 * 创建测试用户
	 * @param code
	 * @param req
	 * @return
	 */
	@Path("/createAccount")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> createAccount(
			@Context HttpServletRequest req) {
		
		for(int i=100;i<401;i++) {
			String psw =generalPassword("19900000"+String.valueOf(i), "123456");
			CompanyVo companyVo =new CompanyVo();
			companyVo.setMobile("19900000"+String.valueOf(i));
			companyVo.setPassword(psw);
			companyVo.setCompanyId(new RandomUtil().getRandomId());
			service.saveCompany(companyVo);
		}
		return ResultCode.success("创建账号成功", null);
		
	}
	
	/**
	 * 获取企业列表
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param companyType 0:正常 1：热门 2：所有
	 * @param req
	 * @return
	 */
	@Path("/queryCompanyList")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryCompanyList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("companyType") final int companyType,
			@Context HttpServletRequest req) {
		try {
			SimpleModelVo vo = new SimpleModelVo();
			List<CompanyVo> list = service.queryCompanyList(pageNo, pageSize, companyType);
			vo.setCompanyList(list);
			vo.setCount(service.queryAllCompanyCount(companyType));
			return ResultCode.success("查询成功", vo);
		} catch (Exception e) {
			return ResultCode.error("查询企业失败", null);
		}
	}
	
	/**
	 * 附近的企业
	 * @param pageNo
	 * @param pageSize
	 * @param longitude 经度
	 * @param latitude 纬度
	 * @param distance 距离
	 * @param req
	 * @return
	 */
	@Path("/queryNearbyCompany")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryNearbyCompany(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("longitude") final String longitude,
			@QueryParam("latitude") final String latitude, @QueryParam("distance") final int distance,
			@Context HttpServletRequest req) {
		
		logger.info("坐标为-----》 longitude="+longitude +"   ,latitude="+latitude);
		
		return service.queryNearbyCompany(pageNo, pageSize, longitude, latitude, distance);
	}
	
	@Path("/uploadRxcel")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public void uploadRxcel(
			@Context HttpServletRequest req) throws IOException {
		
		String fileName ="position1.xlsx";
		File f =new File("E:\\position1.xlsx");
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

		InputStream in = new FileInputStream(f);
        Workbook hb = null;
        if (fileType.equals("xls")) {
            hb = new HSSFWorkbook(in);
        }
        else if (fileType.equals("xlsx")) {
            hb = new XSSFWorkbook(in);
        }
        Sheet sheet = hb.getSheetAt(0);
        for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
        	Row row = sheet.getRow(rowIndex);
        	// 一级
        	String f1 = getCellValue(row.getCell(1), true);
        	// 二级
        	String f2 = getCellValue(row.getCell(2), true);
        	// 三级（分割）
        	String f3 = getCellValue(row.getCell(3), true);
        	
        	if(StringUtil.isEmptyString(f1)) {
        		continue;
        	}
        	
        	// 第一级
        	PostInformation p1 =service.queryPostByName(f1);
        	String id1 =new RandomUtil().getRandomId();
        	if(p1!=null) {
        		id1 =p1.getPostInformationId();
        	}
        	PostInformation pi1 =new PostInformation();
        	pi1.setParentId("0");
        	pi1.setCreateDate(new Date());
        	pi1.setPostInformationId(id1);
        	pi1.setPostInformationName(f1);
        	
        	if(p1==null) {
        		service.save(pi1);
        	}
        	
        	// 第二级
        	p1 =service.queryPostByName(f2,id1);
        	String id2 =new RandomUtil().getRandomId();
        	if(p1!=null) {
        		id2 =p1.getPostInformationId();
        	}
        	PostInformation pi2 =new PostInformation();
        	pi2.setParentId(id1);
        	pi2.setCreateDate(new Date());
        	pi2.setPostInformationId(id2);
        	pi2.setPostInformationName(f2);
        	if(p1==null) {
        		service.save(pi2);
        	}
        	
        	String [] ps =f3.split(" ");
        	if(ps.length>0) {
        		for(String s :ps) {
        			
        			String id3 =new RandomUtil().getRandomId();
                	PostInformation pi3 =new PostInformation();
                	pi3.setParentId(id2);
                	pi3.setCreateDate(new Date());
                	pi3.setPostInformationId(id3);
                	pi3.setPostInformationName(s);
                	// 第三级
                	p1 =service.queryPostByName(s);
                	//if(p1==null) {
                		service.save(pi3);
                	//}
                	
        		}
        	}
        }
        
	}
	
	 private static String getCellValue(Cell cell, boolean treatAsStr) {
	        if (cell == null) {
	            return "";
	        }

	        if (treatAsStr) {
	            // 铏界劧excel涓缃殑閮芥槸鏂囨湰锛屼絾鏄暟瀛楁枃鏈繕琚閿欙紝濡傗��1鈥濆彇鎴愨��1.0鈥�
	            // 鍔犱笂涓嬮潰杩欏彞锛屼复鏃舵妸瀹冨綋鍋氭枃鏈潵璇诲彇
	            cell.setCellType(Cell.CELL_TYPE_STRING);
	        }

	        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
	            return String.valueOf(cell.getBooleanCellValue());
	        }
	        else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
	            return String.valueOf(cell.getNumericCellValue());
	        }
	        else {
	            return String.valueOf(cell.getStringCellValue());
	        }
	    }
}
